/**
 * Stutter.java - a class for detecting duplicate words.  
 * @author  Yosef Zidell
 * @version 1.0 
 */ 
import java.io.*;

import java.util.*;

/**
 * The Class Stutter.
 */ 
public class Stutter {
	/** characters to ignore. */
	private static final Character[] ignoredCharacters_ = {'\0', '\n', '	',
	                                                       ' ', ',', '.', '!',
	                                                       '-', '+', '=', ';',
	                                                       ':', '?', '&', '{',
	                                                       '}', '\\'};

	/**
	 * runs the program.
	 *
	 * @param args the filename
	 */
	public static void main( String[] args ) {
		// no filename found
		if ( args.length < 1 ) {
			System.out.println("Please specify a filename. Usage: java Stutter <path/to/filename>");
			System.exit(1);
		}

		try{
			// get stutterings and display results
			for ( String stuttering : Stutter.getStutterings( args[0] ) )
				System.out.println( stuttering );
		}
		catch ( IOException e ) {
			System.out.println("Could not find file: " + args[0]);
			System.exit(1);
		}
	}

	/**
	 * checks the file contents for duplicate words (stutterings).
	 *
	 * @param  filename the filename
	 * @return ArrayList<String> a list of occurrences
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	public static ArrayList<String> getStutterings( String filename )
			throws IOException {
		ArrayList<String> stutterings = new ArrayList<String>();
		String            previousWord = null;
		BufferedReader    reader = new BufferedReader( new FileReader( filename ) );
		String            line = reader.readLine();
		int               lineNumber = 0;
		String[]          words;

		while ( line != null ) {
			lineNumber++;
			words = line.split(" ");
			for (String word : words ) {
				word = Stutter.deleteCharacters( word );

				// compare with previous word
				if ( word.equals( previousWord ) ) {
					stutterings.add("Repeated word on line " + lineNumber + 
									": " + previousWord + " " + word);
				}

				// update "previous" word
				previousWord = word;
			}

			line = reader.readLine();
		}

		reader.close();

		return stutterings;
	}

	/**
	 * Gets the ignored characters.
	 *
	 * @return the ignored characters
	 */
	public static Character[] getIgnoredCharacters() {
		return Stutter.ignoredCharacters_;
	}

	/**
	 * Deletes certain characters from a word.
	 *
	 * @param  string the string
	 * @return String the word without the characters
	 */
	public static String deleteCharacters( String string ) {
		String output = string;
		for ( Character c : getIgnoredCharacters() ) {
			output = output.replace(c, ' ');
		}

		return output;
	}
}
